package org.example;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

public class SkinAnalysisExample {
    private static final String API_KEY = "3UznLENkCCGHI1VBxtqlfzxy2Rg6zv6J";
    private static final String SECRET_KEY = "g3iL_gem_67PeKi96nVUGNinjDYeZGqn";
    // 高级版
    private static final String API_URL = "https://api-cn.faceplusplus.com/facepp/v1/skinanalyze_advanced";

    public static void main(String[] args) {
        // 图片路径
        File imageFile = new File("C:\\Users\\Administrator\\Pictures\\mz\\demo-pic-skinAnalysis-1.jpg");
        try {
            String result = analyzeSkin(imageFile);
            splitJson(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String analyzeSkin(File imageFile) throws IOException {
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(API_URL);

        // 添加请求参数
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addTextBody("api_key", API_KEY);
        builder.addTextBody("api_secret", SECRET_KEY);
        builder.addBinaryBody("image_file", imageFile, ContentType.APPLICATION_OCTET_STREAM, imageFile.getName());

        HttpEntity multipart = builder.build();
        httpPost.setEntity(multipart);

        // 执行请求
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();

        // 获取响应结果
        String responseString = EntityUtils.toString(responseEntity);

        // 解析 JSON 并获取 "result" 部分
        JSONObject jsonObject = new JSONObject(responseString);
        JSONObject resultObject = jsonObject.getJSONObject("result");

        return resultObject.toString();
    }

    public static void splitJson(String jsonString) {
        JSONObject jsonObject = new JSONObject(jsonString);
        for (String key : jsonObject.keySet()) {
            Object value = jsonObject.get(key);
            System.out.println(key + ": " + value);
        }
    }
}